package core

import (
	"fmt"
	"sync"
)

/*
   玩家管理模块
*/

type OccupantManager struct {
	Occupants 	map[uint32]*Occupant	//管理的玩家信息
	playerLock    sync.RWMutex        //读写玩家的读写锁
}

//提供一个对外的世界管理模块句柄
var OccupantMgrObj *OccupantManager

/*
   创建一个玩家管理模块
*/
func init(){
	OccupantMgrObj = &OccupantManager{
		Occupants: make(map[uint32] *Occupant),
	}
}

//添加玩家
func (ocMgr *OccupantManager) Add(player *Occupant) {
	//保护共享资源Map 加写锁
	ocMgr.playerLock.Lock()
	defer ocMgr.playerLock.Unlock()

	//将玩家添加到PlayerManager中
	ocMgr.Occupants[player.Pid] = player

	fmt.Println("occupant add to OccupantManager successfully: occupant num = ", ocMgr.Len())
}

func (ocMgr *OccupantManager) GetOccupantByPid(pid uint32) *Occupant{
	//保护共享资源Map 加写锁
	ocMgr.playerLock.Lock()
	defer ocMgr.playerLock.Unlock()

	return ocMgr.Occupants[pid]
}

//删除玩家
func (ocMgr *OccupantManager) RemoveOccupantByPid(pid uint32){
	//保护共享资源Map 加写锁
	ocMgr.playerLock.Lock()
	defer ocMgr.playerLock.Unlock()

	//将玩家添加到PlayerManager中
	delete(ocMgr.Occupants, pid)

	fmt.Println("Occupant Remove pid=",pid, " successfully: Occupant num = ", ocMgr.Len())
}

//获取所有玩家的信息
func (ocMgr *OccupantManager) GetAllOccupants() []*Occupant {
	ocMgr.playerLock.RLock()
	defer ocMgr.playerLock.RUnlock()

	//创建返回的player集合切片
	Occupants := make([]*Occupant, 0)

	//添加切片
	for _, v := range ocMgr.Occupants {
		Occupants = append(Occupants, v)
	}

	//返回
	return Occupants
}

//获取玩家池玩家数量
func (ocMgr *OccupantManager) Len() int{
	return len(ocMgr.Occupants)
}